package com.usc.csci588.chaltrojan.login;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.usc.csci588.chaltrojan.R;
import com.usc.csci588.chaltrojan.ui.main.SendLocationUpdate;
//import com.usc.csci588.chaltrojan.NetworkProperties;

public class JoinTripActivity extends Activity {
	
	Button joinButton;	
	TextView tripname_tv ;
	TextView password_tv ;
	String joinreq;
	String updatereq;
	String res;
	//NetworkProperties np;
	String tn, tp, handle;
	
	public boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}
	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.join_trip_form_layout);
		
		joinButton = (Button)findViewById(R.id.join_trip_submit_button);
		tripname_tv = (TextView)findViewById(R.id.join_trip_name);
		password_tv = (TextView)findViewById(R.id.join_trip_password);
		//np = new NetworkProperties();

		
		joinButton.setOnClickListener(new OnClickListener() {		
			
			@Override
			public void onClick(View v) {

				// TODO Auto-generated method stub				
				Log.d("join","Submitted join trip request");				
				joinreq = generateJoinRequest();
				
				
				Log.d("join",joinreq);
				if(isNetworkAvailable())
				{
					
					
				new ServerJoinRequestHandler().execute(joinreq);
				LocationManager lm = (LocationManager) JoinTripActivity.this.getSystemService(Context.LOCATION_SERVICE);				
				Location myLocation;
				myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);		        

		        if (myLocation == null) {
		        	
		        	myLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		        	if (myLocation == null) {
			        	myLocation = new Location("");
			        	myLocation.setLatitude(34.0);
			        	myLocation.setLongitude(-118.0);
		        	}
		        }
		        
		       Log.d("updateLocation","I am about to update the location from JOIN.");
		       SendLocationUpdate slu = new SendLocationUpdate(myLocation.getLatitude(), myLocation.getLongitude());
				SharedPreferences settings = getSharedPreferences("HANDLE",0);
				String handle = settings.getString("handle", "default_user");
		       slu.execute(handle);
		       Log.d("updateLocation","I called the constructor and now I am done.");	
				
				}
				else
				{
					Toast.makeText(getBaseContext(), "Unable to connect to the internet..",Toast.LENGTH_LONG).show();
				}
			}
		});	
		
	}
	
	public String generateJoinRequest()
	{		
		tn = tripname_tv.getText().toString();
		tp = password_tv.getText().toString();
		SharedPreferences settings = getSharedPreferences("HANDLE",0);
		String handle = settings.getString("handle", "default_user");
		String joinURL = Constants.ChalTrojanHostName;
		joinURL += "/ChalTrojan2/JoinTrip?handle="+handle+"&pwd="+tp+"&tripId="+tn;

		return joinURL;
		
	}
	
	public void gotoUpdateData()
	{
		Intent i = new Intent(getApplicationContext(),com.usc.csci588.chaltrojan.login.UpdateTripDataActivity.class);
		i.putExtra(Constants.TripName, tn);
		i.putExtra("userHandle", handle);
        startActivity(i);
        finish();
	}
	
	
	public void onLoginCheck(String response)
	{
		try {
			Log.d("join","I can start the main UI activity here. " + response);		
			if(response.equals("1"))
			{

				Toast.makeText(getBaseContext(), "Joining successful!",Toast.LENGTH_LONG).show();

				// create a new asych task to get update locations.
				//new GetUpdatesOfTrip().execute();
				gotoUpdateData();		

			}
			else
			{
				Toast.makeText(getBaseContext(), "Joining Unsuccessful!",Toast.LENGTH_LONG).show();

			}
		} catch (Exception e){
			Toast.makeText(getBaseContext(), "Unable to contact server - Please check your internet connectivity...",Toast.LENGTH_LONG).show();			
		}
	
	}
	
	
	private class ServerJoinRequestHandler extends AsyncTask<String, Void, Void>	
	{
		ProgressDialog pd;		
		String value;		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pd = ProgressDialog.show(JoinTripActivity.this, "Join Trip Request", "Verifying your request");
		}		
		
		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub			
			String request = params[0];
	        try {        	
	        	
	        	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();        	
				DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();				
				Document document = documentBuilder.parse(request);
				Log.d("join","Got here.");
				NodeList successList = document.getElementsByTagName("success");
				Log.d("join","Length is "+successList.getLength());
				Node s = successList.item(0);				
				value = s.getTextContent();				
				Log.d("join", value+"is value");			
				
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
	      /*
	        document = documentBuilder.parse(response, null);
	        document.getDocumentElement().normalize();
	        NodeList videosList = document.getElementsByTagName("Video");
	        for (int i = 0; i < videosList .getLength(); i++) 
	        {
	                     Node node = videosList .item(i);
	            Element playlistElement = (Element) node;
	            NodeList title = playlistElement.getElementsByTagName("name");
	            if (title.item(0).getChildNodes().item(0) != null) 
	            {   
	                Element nameElement = (Element) title.item(0);
	                title = nameElement.getChildNodes();
	                Log.v("name===>",((Node) title.item(0)).getNodeValue());
	            }

	//Like wise use the same code for title ,url ,thumbnail...
	        }
			
			*/ catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e){
				//Toast.makeText(JoinTrip, text, duration)
			}
						
			return null;			
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pd.dismiss();
			onLoginCheck(value);			
		}
		
	
		
	}
	
	
}